package util


import (
	"context"
	"github.com/go-redis/redis/v8"
	"strconv"
)

type IdClient struct {
	db  *redis.Client
	ctx context.Context
}

func NewIdClient(option *redis.Options) *IdClient {
	return &IdClient{
		ctx: context.Background(),
		db:  redis.NewClient(option),
	}
}

func (s *IdClient) Current(key string) (int64, error) {
	val, err := s.db.Get(s.ctx, key).Result()
	if err != nil {
		if err == redis.Nil {
			// 设置KEY
			err = s.db.Set(s.ctx, key, 0, 0).Err()
			if err != nil {
				panic(err)
			} else {
				val, err = s.db.Get(s.ctx, key).Result()
			}
		} else {
			return 0, err
		}
	}
	v, err := strconv.ParseInt(val, 10, 64)
	return v, err
}

func (s *IdClient) Next(key string) (int64, error) {
	_, err := s.Current(key)
	if err != nil {
		return 0, err
	}
	return s.db.Incr(s.ctx, key).Result()
}

